package com.firefly.mobile.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.content.Context;

public class FileUtils {

	
	/** 
	 * 删除目录（文件夹）以及目录下的文件 
	 * @param   sPath 被删除目录的文件路径 
	 * @return  目录删除成功返回true，否则返回false 
	 */  
	public static boolean deleteDirectory(String sPath) {  
		boolean flag = false;
	    //如果sPath不以文件分隔符结尾，自动添加文件分隔符  
	    if (!sPath.endsWith(File.separator)) {  
	        sPath = sPath + File.separator;  
	    }  
	    File dirFile = new File(sPath);  
	    //如果dir对应的文件不存在，或者不是一个目录，则退出  
	    if (!dirFile.exists() || !dirFile.isDirectory()) {  
	        return false;  
	    }  
	    flag = true;  
	    //删除文件夹下的所有文件(包括子目录)  
	    File[] files = dirFile.listFiles();  
	    for (int i = 0; i < files.length; i++) {  
	        //删除子文件  
	        if (files[i].isFile()) {  
	            flag = deleteFile(files[i].getAbsolutePath());  
	            if (!flag) break;  
	        } //删除子目录  
	        else {  
	            flag = deleteDirectory(files[i].getAbsolutePath());  
	            if (!flag) break;  
	        }  
	    }  
	    if (!flag) return false;  
	    //删除当前目录  
	    if (dirFile.delete()) {  
	        return true;  
	    } else {  
	        return false;  
	    }  
	}  
	
	/** 
	 * 删除单个文件 
	 * @param   sPath    被删除文件的文件名 
	 * @return 单个文件删除成功返回true，否则返回false 
	 */  
	public static boolean deleteFile(String sPath) {  
		boolean flag = false;  
		File file = new File(sPath);  
	    // 路径为文件且不为空则进行删除  
	    if (file.isFile() && file.exists()) {  
	        file.delete();  
	        flag = true;  
	    }  
	    return flag;  
	}  
	
	/**
	 * 移动ASSERT目录下文件至目标路径
	 * 
	 * @param context
	 *            上下文
	 * @param sourcPath
	 *            源文件夹目录
	 * @param targetPath
	 *            目标文件夹目录
	 * @param replace
	 *            若文件存在，是否替换
	 * @throws SytException
	 */
	public static void transAssetsFile(Context context, String sourcPath,
			String targetPath, boolean replace) throws SytException {

		InputStream is = null;
		FileOutputStream fos = null;
		try {
			String str[] = context.getAssets().list(sourcPath);
			if (str.length > 0) {// 如果是目录
				File file = new File(targetPath + File.separator + sourcPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				for (String string : str) {
					sourcPath = sourcPath + File.separator + string;
					transAssetsFile(context, sourcPath, targetPath, replace);
					sourcPath = sourcPath.substring(0,
							sourcPath.lastIndexOf('/'));
				}
			} else {// 如果是文件
				File targetFile = new File(targetPath + File.separator + sourcPath); 
				if (!replace) {
					if (targetFile.exists()) {
						return;
					}
				}
				targetFile.delete();
				is = context.getAssets().open(sourcPath);
				fos = new FileOutputStream(new File(targetPath + File.separator
						+ sourcPath));
				byte[] buffer = new byte[1024 * 8];
				int ch = -1;
				while ((ch = is.read(buffer)) != -1) {
					fos.write(buffer, 0, ch);
				}
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}

		} catch (IOException e) {
			throw new SytException(RespStatus.SYS_ERR, e.toString());
		}
	}

	/**
	 * 移动指定文件件至目标文件
	 * 
	 * @param context
	 * @param sourcFolderPath
	 * @param targetFolderPath
	 * @return
	 * @throws SytException
	 */
	public static boolean transFiles(Context context, String sourcFolderPath,
			String targetFolderPath) throws SytException {
		FileInputStream is = null;
		FileOutputStream fos = null;
		try {
			File folder = new File(sourcFolderPath);
			File[] files = folder.listFiles();
			for (File file : files) {
				is = new FileInputStream(file);
				fos = new FileOutputStream(new File(targetFolderPath
						+ File.separator + file.getName()));
				byte[] buffer = new byte[1024 * 8];
				int ch = -1;
				while ((ch = is.read(buffer)) != -1) {
					fos.write(buffer, 0, ch);
				}
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return true;
		} catch (IOException e) {
			throw new SytException(e.toString());
		}
	}

	/**
	 * 移动指定 文件 至目标文件件
	 * 
	 * @param context
	 * @param sourceFilePath
	 * @param targetFolderPath
	 * @return
	 * @throws SytException
	 */
	public static boolean transFile(Context context, String sourceFilePath,
			String targetFolderPath) throws SytException {
		FileInputStream is = null;
		FileOutputStream fos = null;
		try {
			File file = new File(sourceFilePath);
			if (!file.exists()) {
				throw new SytException("文件：" + sourceFilePath + " 不存在");
			}

			is = new FileInputStream(file);
			fos = new FileOutputStream(new File(targetFolderPath
					+ File.separator + file.getName()));
			byte[] buffer = new byte[1024 * 8];
			int ch = -1;
			while ((ch = is.read(buffer)) != -1) {
				fos.write(buffer, 0, ch);
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return true;
		} catch (IOException e) {
			throw new SytException(e.toString());
		}
	}
	
	
	public static boolean getFilesByPostfix(String fix, String path, List<String> retFiles) throws SytException {
		try {
			File file = new File(path);
			if (!file.exists()) {
				return false;
			}
			File[] existFiles = file.listFiles();
			for (File existFile : existFiles) {
				if (existFile.isDirectory()) {
					getFilesByPostfix(fix, existFile.getPath(), retFiles);
				} else {
					if (existFile == null || !existFile.getPath().endsWith(fix)) {
						continue;
					}
					retFiles.add(existFile.getPath());
				}
			}
			return true;
		} catch (Exception e) {
			throw new SytException(e.toString());
		}
	}
	
	/**
	 * 根据文件路径判断文件是否存在
	 * 
	 * @param path 文件路径
	 * @return 存在返回true,否则返回false
	 */
	public static boolean isFileExist(String path) {
		boolean v = false;
		try {
			File f = new File(path);
			v = f.exists();
		} catch (Exception e) {
			// do nothing
		}
		return v;
	}
}
